// components/popup/popup.js
import user from '../../utils/user.js'
import {
    encryptedPhoneData,
    encryptedUserData
} from '../../api/app.js'
const app = getApp()
Component({
    /**
	 * 组件的属性列表
	 */
    properties: {
        type: String,
        content: String
    },

    /**
	 * 组件的初始数据
	 */
    data: {

    },

    /**
	 * 组件的方法列表
	 */
    methods: {
        getUser(res) {
            if (!user.session_key) {
                app.alert('操作过于频繁，请重新打开小程序').then(() => {
                    wx.reLaunch({
                        url: '/pages/index/index',
                    })
                })
                return
            }
            const data = {
                encryptedData: res.detail.encryptedData,
                sessionKey: user.session_key,
                iv: res.detail.iv
            }
            encryptedUserData(data).then(res => {
                user.avatarUrl = res.avatarUrl
                app.toast('授权成功')
                this.triggerEvent('complete')
            })
        },
        getPhoneNumber(res) {
            if (!user.session_key) {
                app.alert('操作过于频繁，请重新打开小程序').then(() => {
                    wx.reLaunch({
                        url: '/pages/index/index',
                    })
                })
                return
            }
            if(!res.detail.encryptedData){
                app.toast('请检查网络是否稳定，后重新获取手机号')
                return
            }
            const data = {
                appId: app.globalData.appId,
                encryptedData: res.detail.encryptedData,
                sessionKey: user.session_key,
                iv: res.detail.iv
            }
            encryptedPhoneData(data).then(res => {
                user.phoneNum = res.phoneNumber
                app.toast('授权成功')
                this.triggerEvent('complete', res.phoneNumber)
            })
        },
        onTap() {
            switch (this.data.type) {
                case 'subscription':
                    // 获取通知权限
                    wx.requestSubscribeMessage({
                        tmplIds: ['D0FrM_HDo2z7wm3YFbtfkXnciUAycNpXzmUcDbHYR30'],
                        success: () => {
                            app.toast('获取授权成功')
                        },
                        fail: () => {
                            app.toast('授权失败')
                        },
                        complete: () => {
                            this.triggerEvent('complete')
                        }
                    })
                    break
            }
        }
    }
})